package com.jf3q.front.controller;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.PutObjectRequest;
import com.aliyun.oss.model.PutObjectResult;
import com.jf3q.common.vo.ResultVo;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.util.UUID;

@RestController
public class updateImgController {

    @Value("${ali.endpoint}")
    private String endpoint;
    @Value("${ali.https.endpoint2}")
    private String endpoint2;
    @Value("${ali.accessKeyId}")
    private String accessKeyId;
    @Value("${ali.secretAccessKey}")
    private String accessKeySecret;
    @Value("${ali.bucketName}")
    private String bucketName;
//上传照片
    @PostMapping("/oss/{type}")
    public ResultVo upload(@PathVariable String type, MultipartFile file) throws com.aliyuncs.exceptions.ClientException {
        if (file == null || file.isEmpty()) {
            return ResultVo.error("文件必填");
        }
        String originalFilename = file.getOriginalFilename();
        String substring = originalFilename.substring(originalFilename.lastIndexOf("."));
        String fileName = UUID.randomUUID().toString().replace("-", "") + substring;

        StringBuffer objectName = new StringBuffer();
        objectName.append(type + "/" + fileName);

        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        try {
            // 创建PutObjectRequest对象。
            PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, objectName.toString(), file.getInputStream());
            // 上传字符串。
            PutObjectResult result = ossClient.putObject(putObjectRequest);
            System.err.println(result);
            String url="https://"+bucketName+"."+endpoint2+"/"+objectName;
            return ResultVo.success("上传成功",url);
        } catch (Exception oe) {
            return ResultVo.error("上传阿里云失败");
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }
}
